package cn.com.open.ms.ecgpaasdatarest.config;

import cn.com.open.ms.ecgpaasdatarest.interceptor.VerifySignatureInterceptor;
import cn.com.open.ms.ecgpaasdatarest.log.CorsFilter;
import cn.com.open.ms.ecgpaasdatarest.log.LogFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
@EnableTransactionManagement
@EnableAsync
public class SystemConfig extends WebMvcConfigurerAdapter {

    @Bean
    public VerifySignatureInterceptor verifySignatureInterceptor() {
        return new VerifySignatureInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(verifySignatureInterceptor()).excludePathPatterns("/dnotdelet/mom.html").excludePathPatterns("/api/v1/dataMonitor");
        super.addInterceptors(registry);
    }

    @Bean
    public LogFilter getLogFilter() {
        return new LogFilter();
    }

    @Bean
    public CorsFilter corsFilter() {
        return new CorsFilter();
    }

    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(getLogFilter());
        registration.addUrlPatterns("/api/*");
        registration.setName("LogFilter");
        registration.setOrder(2);
        return registration;
    }

    @Bean
    public FilterRegistrationBean corsfilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(corsFilter());
        registration.addUrlPatterns("/api/*");
        registration.setName("CorsFilter");
        registration.setOrder(1);
        return registration;
    }


    @Bean
    public RestTemplate getRestTemplatee() {
        return new RestTemplate();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(false)
                .maxAge(3600);
        super.addCorsMappings(registry);
    }

}
